package com.udf.hive.udf;

import org.apache.hadoop.hive.ql.exec.UDF;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class IdNum2BirthDay extends UDF {
    private DateTimeFormatter inputDateFormate = DateTimeFormatter.ofPattern("yyyyMMdd");
    String outPutDateFormate = "yyyy-MM-dd";

    public String evaluate(String input, String dateFormate) {
        if (dateFormate != null && !dateFormate.trim().isEmpty()) {
            this.outPutDateFormate = dateFormate;
        }
        if (input != null) {
            String idNumTrim = input.trim();
            if (idNumTrim.length() == 18) {
                String birthDayStr = input.substring(6, 14);
                LocalDate birthDay = LocalDate.parse(birthDayStr, inputDateFormate);
                return birthDay.format(DateTimeFormatter.ofPattern(this.outPutDateFormate));
            } else if (idNumTrim.length() == 15) {
                String birthDayStr = input.substring(6, 12);
                LocalDate birthDay = LocalDate.parse("19"+birthDayStr, inputDateFormate);
                return birthDay.format(DateTimeFormatter.ofPattern(this.outPutDateFormate));
            }
        }
        return "";
    }

    public String evaluate(String input) {
        if (input != null) {
            String idNumTrim = input.trim();
            if (idNumTrim.length() == 18) {
                String birthDayStr = input.substring(6, 14);
                LocalDate birthDay = LocalDate.parse(birthDayStr, inputDateFormate);
                return birthDay.format(DateTimeFormatter.ofPattern(this.outPutDateFormate));
            } else if (idNumTrim.length() == 15) {
                String birthDayStr = input.substring(6, 12);
                LocalDate birthDay = LocalDate.parse("19"+birthDayStr, inputDateFormate);
                return birthDay.format(DateTimeFormatter.ofPattern(this.outPutDateFormate));
            }
        }
        return "";
    }
}
